package com.nibianplus.base;

import com.nibianplus.volley.JSONResponseCallback;
import com.nibianplus.volley.VolleyConfig;
import com.nibianplus.volley.VolleyHttpClient;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;

public abstract class BaseObject extends JSONResponseCallback {

	BaseObjectListener listener;

	protected JSONObject data;

	VolleyConfig config = new VolleyConfig();

	public void setNeedCache(boolean cache) {
		config.setShouldCache(cache);
	}

	public BaseObject(String tag) {
		config.setTag(tag);
	}

	public void post(String url, Map<String, Object> map, int what) {
		VolleyHttpClient.post(url, map, this, what, config);
	}

	public void form(String url, Map<String, Object> map, Map<String, File> files, int what) {
		VolleyHttpClient.form(url, map, files, this, what);
	}

	public void form2(String url, Map<String, Object> map, Map<String, List<File>> files, int what) {
		VolleyHttpClient.form2(url, map, files, this, what);
	}

	public void get(String url, Map<String, String> map, int what) {
		VolleyHttpClient.get(url, map, this, what, config);
	}

	public void setListener(BaseObjectListener listener) {
		this.listener = listener;
	}

	public void refresh() {
		loadData();
	}

	public abstract void loadData();

	public void parseResult(int what, JSONObject response) {
		// data = response.optJSONObject("data");
		data = response;
	}

	public JSONArray getJSONArray(String key) {
		if (data != null)
			return data.optJSONArray(key);
		else
			return null;
	}

	public JSONObject getJSONObject(String key) {
		if (data != null)
			return data.optJSONObject(key);
		else
			return null;
	}

	public JSONObject getData() {
		return data;
	}

	public String getString(String key) {
		if (data != null)
			return data.optString(key);
		else
			return null;
	}

	public Integer getInt(String key) {
		if (data != null)
			return data.optInt(key);
		else
			return null;
	}

	public void notifyDataObjectChanged(int what) {
		if (listener != null) {
			listener.dataObjectChanged(this, what);
		}
	}

	@Override
	public void done(int what, JSONObject response) {
		parseResult(what, response);

		notifyDataObjectChanged(what);
	}

	@Override
	public void error(int what, JSONObject response) {
		if (listener != null) {
			listener.dataObjectFailed(this, what, response);
		}
	}

}
